﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

namespace ET.Monitor.DAL
{
    public class StringDAL
    {
        object obj = null;
        double dVal = 0;
        string strSql = "", strErrMsg = "";
        DataTable dt = new DataTable();

        InvokeWebService iw = new InvokeWebService();
        string rtdbRelationAddress = "";
        string rtdbRealTimeAddress = "";
        string rtdbNameSpace = "";
        string rtdbJudge = "";

        public StringDAL()
        {
            rtdbRelationAddress = ConfigurationManager.ConnectionStrings["RelationURL"].ConnectionString;
            rtdbRealTimeAddress = ConfigurationManager.ConnectionStrings["RealTimeURL"].ConnectionString;
            rtdbNameSpace = ConfigurationManager.ConnectionStrings["NameSpace"].ConnectionString;
            rtdbJudge = ConfigurationManager.ConnectionStrings["Judge"].ConnectionString;
        }

        #region 获取组串
        public DataTable GetString(string id)
        {
            if (id.IndexOf("'") > -1)
                strSql = "select T_STRINGID,T_STRINGDESC,T_UNITID from T_BASE_STRING where T_UNITID in(" + id + ")";
            else
                strSql = "select T_STRINGID,T_STRINGDESC,T_UNITID from T_BASE_STRING where T_UNITID ='" + id + "'";

            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });

            return dt;
        }
        #endregion

        #region 电压
        public double GetVoltage(string id, DateTime st, DateTime et)
        {
            strSql = "select T_VoltageTAG from T_BASE_POINTS_STRING where T_STRINGID='" + id + "'";
            obj = iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });
            dt = (DataTable)iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetHistValueByStartTimeAndEndTime", new object[] { obj.ToString(), st, et });
            dVal = GetDouble(double.Parse(dt.Compute("avg(Value)", "true").ToString()), 2);
            return dVal;
        }
        #endregion

        #region 平均电流
        public double GetInverternIacr(string id, DateTime st, DateTime et)
        {
            strSql = "select T_CURRENTTAG from T_BASE_POINTS_STRING where T_STRINGID='" + id + "'";
            obj = iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });
            dt = (DataTable)iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetHistValueByStartTimeAndEndTime", new object[] { obj.ToString(), st, et });
            dVal = GetDouble(double.Parse(dt.Compute("Avg(Value)", "true").ToString()), 2);
            return dVal;
        }
        #endregion

        #region 平均功率
        public double GetPower(string id, DateTime st, DateTime et)
        {
            strSql = "select T_POWERTAG from T_BASE_POINTS_STRING where T_STRINGID='" + id + "'";
            obj = iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });
            dt = (DataTable)iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetHistValueByStartTimeAndEndTime", new object[] { obj.ToString(), st, et });
            dVal = GetDouble(double.Parse(dt.Compute("Avg(Value)", "true").ToString()), 2);
            return dVal;
        }
        #endregion

        #region 实时电流
        public double GetRealIacr(string id)
        {
            strSql = "select T_CURRENTTAG from T_BASE_POINTS_STRING where T_STRINGID='" + id + "'";
            obj = iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });
            if (obj != null && obj != "")
                if (rtdbJudge == "1")
                    return GetDouble(Convert.ToDouble(iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValue", new object[] { obj.ToString() })), 2);
                else
                    return GetDouble(Convert.ToDouble(iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValueNoJudge", new object[] { obj.ToString() })), 2);
            else
                return double.NaN;
        }
        #endregion

        #region 电流平均值
        public double GetAvgIacr(string id)
        {
            strSql = "select T_CurrentAVGTAG from T_BASE_POINTS_STRING where T_STRINGID='" + id + "'";
            obj = iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });
            if (obj != null && obj != "")
                if (rtdbJudge == "1")
                    return GetDouble(Convert.ToDouble(iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValue", new object[] { obj.ToString() })), 2);
                else
                    return GetDouble(Convert.ToDouble(iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValueNoJudge", new object[] { obj.ToString() })), 2);
            else
                return double.NaN;
        }
        #endregion

        #region 所属逆变器ID
        public object GetInverterId(string id)
        {
            strSql = "select T_UNITID from T_BASE_STRING where T_STRINGID='" + id + "'";
            return iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });
        }
        #endregion

        #region 实时电压
        public double GetRealVacr(string id)
        {
            strSql = "select T_VoltageTAG from T_BASE_POINTS_STRING where T_STRINGID='" + id + "'";
            obj = iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });

            if (obj != null)
                if (rtdbJudge == "1")
                    return GetDouble(Convert.ToDouble(iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValue", new object[] { obj.ToString() })), 2);
                else
                    return GetDouble(Convert.ToDouble(iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValueNoJudge", new object[] { obj.ToString() })), 2);
            else
                return double.NaN;
        }
        #endregion

        #region 组串状态
        public int GetStringState(string id)
        {
            int index = 0;
            double avgIacr = GetAvgIacr(id);
            double realIacr = GetRealIacr(id);

            if (double.IsNaN(avgIacr) || double.IsNaN(realIacr)) index = 0;
            else
            {
                if (avgIacr - realIacr > 0)
                {
                    strSql = "select D_PARAWARINGLEVEL1 from T_BASE_SYSPARA";
                    obj = iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });
                    double Waring = 0;
                    Waring = double.Parse(obj.ToString());

                    strSql = "select D_PARAWARINGLEVEL2 from T_BASE_SYSPARA";
                    obj = iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunSingle", new object[] { strSql, strErrMsg });
                    double Halt = 0;
                    Halt = double.Parse(obj.ToString());

                    if (Waring <= (avgIacr - realIacr) / avgIacr * 100 && (avgIacr - realIacr) / avgIacr * 100 < Halt)
                        index = 1;
                    else if ((avgIacr - realIacr) / avgIacr * 100 >= Halt)
                        index = 2;
                    else if ((avgIacr - realIacr) / avgIacr * 100 < Waring)
                        index = 0;
                }
                else index = 0;
            }
            return index;
        }


        public int[] GetStringStateArray(string id)
        {
            int index = 0;
            List<double[]> val = new List<double[]>();
            double[] d_vals = new double[1];
            string str_order = id.Replace("(", "").Replace(")", "").Replace("'", "");
            strSql = "select T_CurrentAVGTAG,T_CURRENTTAG from T_BASE_POINTS_STRING where T_STRINGID in  (" + id + ") order by CHARINDEX(',' + LTRIM(T_STRINGID) + ',', '," + str_order + ",')";



            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });

            string[] str_arr = dt.AsEnumerable().Select(t => t.Field<string>("T_CurrentAVGTAG")).ToArray();
            if (str_arr != null)
            {
                object d_vals1 = null;// iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValues", new object[] { str_arr });
                if (rtdbJudge == "1")
                    d_vals1 = iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValues", new object[] { str_arr });
                else
                    d_vals1 = iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValuesNoJudge", new object[] { str_arr });

                d_vals = (double[])d_vals1;
            }
            val.Add(d_vals);
            //
            str_arr = dt.AsEnumerable().Select(t => t.Field<string>("T_CURRENTTAG")).ToArray();
            if (str_arr != null)
            {
                object d_vals1 = null;
                if (rtdbJudge == "1")
                    d_vals1 = iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValues", new object[] { str_arr });
                else
                    d_vals1 = iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetRealValuesNoJudge", new object[] { str_arr });
                d_vals = (double[])d_vals1;
            }
            val.Add(d_vals);

            strSql = "select D_PARAWARINGLEVEL1,D_PARAWARINGLEVEL2 from T_BASE_SYSPARA";
            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
            double Waring = 0;
            Waring = double.Parse(dt.Rows[0][0].ToString());

            double Halt = 0;
            Halt = double.Parse(dt.Rows[0][1].ToString());
            int[] i_val = new int[val[0].Length];
            for (int i = 0; i < val[0].Length; i++)
            {
                double avgIacr = val[0][i];
                double realIacr = val[1][i];
                if (double.IsNaN(avgIacr) || double.IsNaN(realIacr)) index = 0;
                else
                {
                    if (avgIacr - realIacr > 0)
                    {
                        if (Waring <= (avgIacr - realIacr) / avgIacr * 100 && (avgIacr - realIacr) / avgIacr * 100 < Halt)
                            index = 1;
                        else if ((avgIacr - realIacr) / avgIacr * 100 >= Halt)
                            index = 2;
                        else if ((avgIacr - realIacr) / avgIacr * 100 < Waring)
                            index = 0;
                    }
                    else index = 0;
                }
                i_val[i] = index;
            }


            return i_val;
        }
        #endregion

        #region 四舍五入
        /// <summary>
        /// 四舍五入
        /// </summary>
        /// <param name="result">要转换的数值</param>
        /// <param name="num">保留位数</param>
        /// <returns></returns>
        public double GetDouble(double result, int num)
        {
            if (!double.IsNaN(result))
            {
                string res = result.ToString();
                string results = "";
                int index = res.IndexOf('.');

                if (res.Length - index == num + 1)
                    return Convert.ToDouble(res);
                else
                {
                    if (index > 0)
                    {
                        index += num;
                        res = res + "000000000000000000";
                        res = res.Remove(0, index + 1);
                        results = result + "000000000000000000";
                        results = results.ToString().Substring(0, index + 1);
                        res = res.Substring(0, 1);

                        string point = "0.";

                        for (int count = 0; count < num - 1; count++)
                        {
                            point += "0";
                        }
                        point += "1";


                        if (Convert.ToInt32(res) > 4)
                        {
                            results = (Convert.ToDouble(results) + Convert.ToDouble(point)).ToString();
                            res = results;
                        }
                        else
                        {
                            res = results;
                        }
                    }
                    else
                    {
                        res += ".";
                        for (int i = 0; i < num; i++)
                        {
                            res += "0";
                        }
                    }
                    return Convert.ToDouble(res);
                }
            }
            else
                return result;
        }
        #endregion
        #region by liucy 组串信息增删改

        /// <summary>
        /// 添加组串信息
        /// </summary>
        /// <param name="pvStringId"></param>
        /// <param name="unitId"></param>
        /// <param name="stringDes"></param>
        /// <returns></returns>
        public bool SavePVString(string pvStringId, string unitId, string stringDes, double area, string install, int transformation, string sign, string MACHINEID)
        {
            strSql = "INSERT INTO T_BASE_STRING (T_STRINGID,T_UNITID,T_STRINGDESC,T_AREA,T_INSTALL,T_Transformation,T_SIGN,T_MACHINEID) VALUES ('" + pvStringId + "','" + unitId + "','" + stringDes + "','" + area + "','" + install + "','" + transformation + "','" + sign + "','" + MACHINEID + "')";
            return (bool)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunNonQuery", new object[] { strSql, strErrMsg });
        }



        /// <summary>
        /// 删除组串
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeletePVString(string id)
        {
            strSql = "DELETE FROM T_BASE_STRING WHERE T_STRINGID='" + id + "'";
            return (bool)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunNonQuery", new object[] { strSql, strErrMsg });
        }

        /// <summary>
        /// 更新组串信息
        /// </summary>
        /// <param name="pvStringId"></param>
        /// <param name="stringDes"></param>
        /// <returns></returns>
        public bool UpdatePVString(string pvStringId, string stringDes, double area, string install, int transformation, string sign,string machineId)
        {
            strSql = "UPDATE T_BASE_STRING SET T_STRINGDESC='" + stringDes + "',T_AREA='" + area + "',T_INSTALL='" + install + "',T_Transformation='" + transformation + "',T_SIGN='" + sign + "',T_MACHINEID='"+machineId+"' WHERE T_STRINGID='" + pvStringId + "'";
            return (bool)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunNonQuery", new object[] { strSql, strErrMsg });
        }

        /// <summary>
        /// 根据组串编号获得组串信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DataTable GetDtStringById(string id)
        {
            strSql = "SELECT * FROM T_BASE_STRING WHERE T_STRINGID='" + id + "'";
            return (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
        }

        /// <summary>
        /// 根据组串id获取组串相关信息，包括设备编码，设备公司
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DataTable GetDtStringInfosById(string id)
        {
            strSql = @"SELECT A.*,B.T_COMPANYID FROM dbo.T_BASE_STRING A
            LEFT JOIN dbo.T_BASE_MACHINE B ON A.T_MACHINEID=B.T_MACHINEID
            WHERE A.T_STRINGID='" + id + "'";
            return (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
        }
        #endregion

        #region 离散率曲线
        public double[][] GetDispersionRatioLine(string tag, DateTime sTime, DateTime eTime, int second)
        {
            strSql = "select T_DISPERSIONRATIOTAG from T_BASE_POINTS_STRING where T_STRINGID in(" + tag + ")";

            double[][] val = null;

            dt = (DataTable)iw.RunWebService(rtdbRelationAddress, rtdbNameSpace, "RunDataTable", new object[] { strSql, strErrMsg });
            string[] points = new string[dt.Rows.Count];

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                points[i] = dt.Rows[i][0].ToString();
            }
            val = (double[][])iw.RunWebService(rtdbRealTimeAddress, rtdbNameSpace, "GetHistValuesByStep", new object[] { points, sTime, eTime, second });

            return val;
        }
        #endregion

    }
}
